package se.ramfelt.psn.web.us;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.SimpleTimeZone;

import org.json.JSONException;
import org.json.JSONObject;

import se.ramfelt.psn.model.Friend;
import se.ramfelt.psn.model.TrophySummary;
import se.ramfelt.psn.model.Friend.Presence;

public class FriendFactory {

    private static final SimpleDateFormat OFFLINE_TIMESTAMP_DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
    
    static {
        OFFLINE_TIMESTAMP_DATE_FORMAT.setTimeZone(new SimpleTimeZone(0, "GMT"));
    }

    public Friend createFriend(String jsonString) throws JSONException, ParseException {
        JSONObject root = new JSONObject(jsonString);
        Friend friend = new Friend(root.getString("userName"));
        friend.setAvatarUrl(root.getString("avatar"));

        if (root.has("level")) {
            JSONObject level = root.getJSONObject("level");
            friend.setTrophySummary(new TrophySummary(level.getInt("level"), level.getInt("platinum"), level.getInt("gold"), level.getInt("silver"), level.getInt("bronze")));
        }

        if (root.has("onlineStatus")) {
            JSONObject onlineStatus = root.getJSONObject("onlineStatus");
            if (onlineStatus.isNull("offline")) {
                friend.setPresence(Presence.Online);

                if (!onlineStatus.isNull("extensionStatus")) {
                    JSONObject extensionStatus = onlineStatus.getJSONObject("extensionStatus");
                    String status = extensionStatus.getString("status");
                    if ((status == null) || (status.length() == 0)) {
                        friend.setCurrentGame(extensionStatus.getString("title"));
                    } else {
                        friend.setCurrentGame(extensionStatus.getString("title") + " " + extensionStatus.getString("status"));
                    }
                }

            } else {
                friend.setPresence(Presence.Offline);                
                friend.setLastSeenTimestamp(OFFLINE_TIMESTAMP_DATE_FORMAT.parse(onlineStatus.getJSONObject("offline").getString("stamp")).getTime());
            }
        }

        return friend;
    }
}
